< previous page page_340 next page >

Page 340
Because the Win32 API is written largely in C, most API functions use NULL-terminated strings. The only exceptions are those functions that are part of the OLE subsystem and specifically designed to work with BSTR strings.
You may be wondering how you can include a NULL character in a C string. The answer is simpleyou can't. That's one reason why the BSTR format was developed.
How can you tell if an API function that takes a string parameter expects a Unicode or an ANSI string? The function documentation tells you. In order to provide maximum flexibility, most API functions actually consist of two separate functions, one that handles ANSI strings and another that handles Unicode strings. For example, the GetWindowText function does not actually exist. What you'll find are two functions, GetWindowTextA and GetWindowTextW. The former uses ANSI strings, the latter uses Unicode (wide) strings.
The ANSI declaration is used with Visual Basic as follows:
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
The Alias statement specifies the name of the function within the DLL. Thus, when you refer to "GetWindowText" in Visual Basic, it actually calls the GetWindowTextA function. You will almost always use the ANSI version of a function when calling it from Visual Basic. Why? Because while both Windows 95/98 and Windows NT export Unicode and ANSI versions of most functions, only the ANSI version works on Windows 95/98the Unicode entry point may exist, but it won't do anything. This is illustrated in Figure T5-6.
You've seen that Visual Basic stores strings internally in BSTR Unicode format and that most API functions expect NULL-terminated ANSI strings. That leaves an interesting question: How do you get from here to there?
Passing Strings to DLL Functions
For most Visual Basic programmers, the following two rules are all you will ever need to know about passing strings to DLL or API functions:
Always use ByVal when passing strings as parameters to DLL functions.
If there is any chance that the API or DLL function will modify the string, be sure the string you pass to the function is already long enough to hold the modified string.

 
< previous page page_340 next page >